/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.google.shop.product.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
//import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class MR extends HashMap<String, Object> {
//	private static final long serialVersionUID = 1L;

    //利用fastjson
    public <T> T getData(TypeReference<T> typeReference){
        Object data = get("data"); //默认map
        String jsonString = JSON.toJSONString(data);//先转成json
        T t = JSON.parseObject(jsonString, typeReference);//再转回泛型
        return t;
    }

    //可以取自定义的key
    public <T> T getData(String key, TypeReference<T> typeReference){
        Object data = get(key); //默认map
        String jsonString = JSON.toJSONString(data);
        T t = JSON.parseObject(jsonString, typeReference);
        return t;
    }

    public MR setData(Object data){
        put("data", data);
        return this;
    }

    public MR() {
        put("code", 0);
        put("msg", "success");
    }

//	public static R error() {
//		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
//	}
//
//	public static R error(String msg) {
//		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
//	}

    public static MR error() {
        return error(1, "未知异常，请联系管理员");
    }

    public static MR error(String msg) {
        return error(1, msg);
    }

    public static MR error(int code, String msg) {
        MR r = new MR();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static MR ok(String msg) {
        MR r = new MR();
        r.put("msg", msg);
        return r;
    }

    public static MR ok(Map<String, Object> map) {
        MR r = new MR();
        r.putAll(map);
        return r;
    }

    public static MR ok() {
        return new MR();
    }

    public MR put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public  Integer getCode() {

        return (Integer) this.get("code");
    }
}
